<script setup lang="ts">
import { ref, h, reactive } from "vue";
import {
  queryTeacherList,
  addTeacher,
  editTeacher,
  deleteTeacher,
  queryStoreList,
  getSkillList,
  getTeacherDetail,
  enums
} from "@/api/teacher";
import { uploadUrl } from "@/api/global";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import type { UploadProps } from "element-plus";
import { request } from "http";
defineOptions({
  name: "teacher"
});
const currentPage = ref(1);
const pageSize = ref(10); // 添加这行

const pageTotal = ref(0);
let tableData = ref([]);
const type = ref("");
let previewUrl = ref("");
const queryParams = reactive({
  teacherName: "",
  phoneNum: "",
  nickName: "",
  storeId: "",
  status: ""
});
//老师状态
const teacherStatusList = ref([]);
enums({ code: "TeacherStatus" }).then((res: any) => {
  teacherStatusList.value = res.data;
});
//门店列表
initStoreList();
//技能列表
initSkillList();
//初始化列表
queryListTableData();

//查询列表
function queryListTableData(params?) {
  const _params = {
    pageNo: 1,
    pageSize: 10,
    total: 0,
    ...params
  };
  if (queryParams.teacherName) {
    _params.teacherName = queryParams.teacherName;
  }
  if (queryParams.phoneNum) {
    _params.phoneNum = queryParams.phoneNum;
  }
  if (queryParams.nickName) {
    _params.nickName = queryParams.nickName;
  }
  if (queryParams.storeId) {
    _params.storeId = queryParams.storeId;  // 门店ID
  }
  if (queryParams.status) {
    _params.status = queryParams.status;  // 老师状态
  }
  queryTeacherList({ ..._params }).then((res: any) => {
    console.log(res, "res");
    tableData.value = res.data.data;
    pageTotal.value = res.data.total;
  });
}

//性别
const genderList = ref([]);
enums({ code: "Gender" }).then((res: any) => {
  genderList.value = res.data;
});
// 门店列表
const storeList = ref([]);
function initStoreList() {
  const params = {
    pageNo: 1,
    pageSize: 10,
    storeName: ""
  };
  queryStoreList(params).then((res: any) => {
    storeList.value = res.data.data;
  });
}

//筛选
const ruleFormRef = ref<FormInstance>();

const validatephoneNum = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入手机号"));
  } else {
    if (ruleForm.phoneNum !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField("phoneNum");
    }
    callback();
  }
};
const ruleForm = reactive({
  nickName: "",
  phoneNum: "",
  teacherName: "",
  age: 0,
  avatar: "",
  enterTime: "",
  skills: [],
  status: "",
  storeId: "",
  birthdayStr: "", //N
  description: "" //N
});

const rules = reactive<FormRules<typeof ruleForm>>({
  phoneNum: [{ required: true, validator: validatephoneNum, trigger: "blur" }],
  teacherName: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  enterTime: [{ required: true, message: "请选择入职时间", trigger: "change" }],
  avatar: [{ required: true, message: "请上传头像", trigger: "change" }],
  storeId: [{ required: true, message: "请选择门店", trigger: "change" }],
  nickName: [{ required: true, message: "请输入昵称", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
  skills: [{ required: true, message: "请选择专业技能", trigger: "change" }]
});

// 重置页面
const onReset = () => {
  queryParams.teacherName = "";
  queryParams.phoneNum = "";
  queryParams.nickName = "";
  queryParams.storeId = "";
  queryParams.status = "";
  pageTotal.value = 0;
  currentPage.value = 1;
  queryListTableData();
};
//查看详情
const detailInfo = reactive({
  teacherName: "",
  phoneNum: "",
  age: "",
  storeName: "",
  nickName: "",
  skills: [],
  enterTime: "",
  avatarUrl: "",
  birthdayStr: "",
  description: "",
  statusName: ""
});
const handleDetailRole = async (row, mark) => {
  addRoleDialogVisible.value = true;
  type.value = mark;
  getTeacherDetail({ teacherId: row.id }).then((res: any) => {
    console.log(res, "res");
    detailInfo.phoneNum = res.data.phoneNum;
    detailInfo.teacherName = res.data.teacherName;
    detailInfo.age = res.data.age;
    detailInfo.storeName = res.data.storeName;
    detailInfo.nickName = res.data.nickName;
    detailInfo.skills = res.data.skillItems;
    detailInfo.enterTime = res.data.enterTime;
    detailInfo.avatarUrl = res.data.avatarUrl;
    detailInfo.birthdayStr = res.data.birthday;
    detailInfo.description = res.data.description;
    detailInfo.statusName = res.data.statusName;
  });
};
//添加
const addRoleDialogVisible = ref(false);
// 在其他 ref 声明附近添加
const skillList = ref([]);

// 在 initStoreList 函数后添加
function initSkillList() {
  const params = {
    pageNo: 1,
    pageSize: 999
  };
  getSkillList(params).then((res: any) => {
    skillList.value = res.data;
  });
}

// 在 handleAddRole 函数中添加技能列表初始化
function handleAddRole(mark) {
  addRoleDialogVisible.value = true;
  type.value = mark;
  Object.keys(ruleForm).forEach(key => {
    ruleForm[key] = key === "skills" ? [] : "";
  });
}
function addRoleInfo() {
  addTeacher({
    teacherName: ruleForm.teacherName,
    phoneNum: ruleForm.phoneNum,
    skills: ruleForm.skills.join(","), // 将数组转换为逗号分隔的字符串
    enterTime: ruleForm.enterTime,
    avatar: ruleForm.avatar,
    birthdayStr: ruleForm.birthdayStr,
    description: ruleForm.description,
    status: ruleForm.status,
    storeId: ruleForm.storeId,
    nickName: ruleForm.nickName,
    age: ruleForm.age
  })
    .then((res: any) => {
      console.log(res);
      ElMessage({
        type: "success",
        message: res.message
      });
      addRoleDialogVisible.value = false;
      queryListTableData();
    })
    .catch((err: any) => {
      console.log(err);
      ElMessage({
        type: "error",
        message: err.message
      });
    });
}
//编辑
const editId = ref("");
const handleEditRole = async (row, mark) => {
  console.log(row, "data");
  previewUrl.value = ""; // 重置预览图片
  let storeId = "";
  if (row.storeName) {
    storeId = storeList.value.find(item => item.storeName === row.storeName).id;
  }
  let statusCode = "";
  if (row.status) {
    statusCode = teacherStatusList.value.find(
      item => item.name === row.status
    ).code;
  }

  let skills = [];
  if (row.skills) {
    // 根据技能名称找到对应的技能ID
    skills = row.skills
      .map(
        skillName =>
          skillList.value.find(item => item.skillName === skillName)?.id
      )
      .filter(id => id !== undefined);
  }
  type.value = mark;
  editId.value = row.id;
  addRoleDialogVisible.value = true;
  ruleForm.phoneNum = row.phoneNum;
  ruleForm.teacherName = row.teacherName;
  ruleForm.age = row.age;
  ruleForm.storeId = storeId;
  ruleForm.nickName = row.nickName;
  ruleForm.skills = skills;
  ruleForm.enterTime = row.enterTime;
  ruleForm.avatar = row.avatarUrl;
  ruleForm.birthdayStr = row.birthday;
  ruleForm.description = row.description;
  ruleForm.status = statusCode;
  console.log(ruleForm, "ruleForm");
};
function editRoleInfo() {
  console.log(ruleForm, "ruleForm");
  editTeacher({
    teacherName: ruleForm.teacherName,
    phoneNum: ruleForm.phoneNum,
    skills: ruleForm.skills.join(","), // 编辑时也需要转换格式
    enterTime: ruleForm.enterTime,
    avatar: ruleForm.avatar,
    birthdayStr: ruleForm.birthdayStr,
    description: ruleForm.description,
    status: ruleForm.status,
    storeId: ruleForm.storeId,
    nickName: ruleForm.nickName,
    age: ruleForm.age,
    id: editId.value
  }).then((res: any) => {
    console.log(res);
    addRoleDialogVisible.value = false;
    ElMessage({
      type: "success",
      message: res.message
    });
    queryListTableData();
  });
}
//提交
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.validate(valid => {
    if (valid) {
      console.log("submit!");
      if (type.value == "add") {
        addRoleInfo();
      } else if (type.value == "edit") {
        editRoleInfo();
      }
    } else {
      console.log("error submit!");
    }
  });
};
//删除用户
const handleDeteleRole = async (record: Recordable) => {
  // const type = await VxeUI.modal.confirm("您确定要删除吗？");
  ElMessageBox.confirm("确认是否删除?", "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning"
  })
    .then(() => {
      deleteTeacher({ teacherId: record.id })
        .then((res: any) => {
          ElMessage({
            type: "success",
            message: "删除成功"
          });
          queryListTableData();
        })
        .catch((err: any) => {
          console.log(err);
          ElMessage({
            type: "error",
            message: err.message
          });
        });
    })
    .catch(() => {
      // ElMessage({
      //   type: "info",
      //   message: "删除失败"
      // });
    });
};
//重置添加用户
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  queryListTableData(val);
};

const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  queryListTableData(val);
};
function handleClose() {
  console.log("关闭");
  addRoleDialogVisible.value = false;
}
// 头像上传成功的回调
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  if (response.code === 200) {
    ElMessage.success("上传成功");
    console.log(response, "response");
    // 使用完整的URL路径
    ruleForm.avatar = response.data.dataUrl;
    // ruleForm.avatar = import.meta.env.VITE_API_URL + response.data;
    // 或者使用相对路径（取决于你的项目配置）
    // uploadFile.url = "https://www.itbenma.com/budcar" + response.data;
    previewUrl.value = response.data.previewUrl;
    console.log(ruleForm.avatar, uploadFile.url, "r");
  } else {
    ElMessage.error(response.msg || "上传失败");
  }
};
// 头像上传前的校验
const beforeAvatarUpload = (file: File) => {
  const isJPG = file.type === "image/jpeg";
  const isPNG = file.type === "image/png";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG && !isPNG) {
    ElMessage.error("上传头像图片只能是 JPG 或 PNG 格式!");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
    return false;
  }
  return true;
};
</script>
<template>
  <div class="statement">
    <div class="search">
      <div class="c-input">
        <el-input
          v-model="queryParams.teacherName"
          clearable
          placeholder="请输入姓名"
        />
      </div>
      <div class="c-input">
        <el-input
          v-model="queryParams.phoneNum"
          clearable
          placeholder="请输入手机号"
        />
      </div>
      <div class="c-input">
        <el-input
          v-model="queryParams.nickName"
          clearable
          placeholder="请输入昵称"
        />
      </div>
      <div class="c-input">
        <el-select
          v-model="queryParams.storeId"
          size="large"
          placeholder="请选择所属门店"
        >
          <el-option
            v-for="item in storeList"
            :key="item.id"
            :label="item.storeName"
            :value="item.id"
          />
        </el-select>
      </div>
      <div class="c-input">
        <el-select
          v-model="queryParams.status"
          size="large"
          placeholder="请选择状态"
        >
          <el-option
            v-for="item in teacherStatusList"
            :key="item.code"
            :label="item.name"
            :value="item.code"
          />
        </el-select>
      </div>
      <div class="search-btn">
        <el-button type="primary" size="large" @click="queryListTableData"
          >查询</el-button
        >
        <el-button size="large" @click="onReset">重置</el-button>
      </div>
    </div>
    <div class="add">
      <el-button type="primary" size="large" @click="handleAddRole('add')"
        ><el-icon><Plus /></el-icon>添加老师信息</el-button
      >
    </div>
    <div class="c-page__bg">
      <el-table :data="tableData">
        <el-table-column prop="teacherName" label="老师姓名" />
        <el-table-column prop="phoneNum" label="手机号码" />
        <el-table-column prop="nickName" label="昵称" />
        <el-table-column label="头像">
          <template #default="scope">
            <el-image
              :src="scope.row.avatarUrl"
              :preview-src-list="[scope.row.avatarUrl]"
               preview-teleported
                :hide-on-click-modal="true"
                fit="cover"
              style="width: 50px; height: 50px;cursor: pointer"
            />
          </template>
        </el-table-column>
        <el-table-column prop="age" label="年龄" />
        <el-table-column prop="birthday" label="生日" />
        <el-table-column prop="storeName" label="所属门店" />
        <el-table-column prop="enterTime" label="入职时间" />
        <el-table-column prop="status" label="状态" />
        <el-table-column prop="skills" label="专业技能">
          <template #default="scope">
            <span v-for="(item, index) in scope.row.skills" :key="index"
              >{{ item }}
              <i v-if="index != scope.row.skills.length - 1">,</i></span
            >
          </template>
        </el-table-column>
        <el-table-column prop="description" label="介绍" min-width="150">
          <template #default="scope">
            <el-tooltip
              class="box-item"
              effect="dark"
              :content="`<span style='width:200px;display:inline-block;white-space:normal;'>${scope.row.description}</span>`"
              raw-content
            >
              <div class="description-cell">{{ scope.row.description }}</div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column
          #default="{ row }"
          label="操作"
          width="220"
          fixed="right"
        >
          <span class="c-text-primary" @click="handleDetailRole(row, 'detail')"
            >详情</span
          >
          <span class="c-text-primary" @click="handleEditRole(row, 'edit')"
            >编辑</span
          >
          <span class="c-text-primary" @click="handleDeteleRole(row)">
            删除
          </span>
        </el-table-column>
      </el-table>
      <div class="pagination-block">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="pageTotal"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :page-sizes="[10, 20, 30, 50]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
    <el-dialog
      v-model="addRoleDialogVisible"
      :title="type == 'detail' ? '查看详情' : '添加/编辑老师信息'"
      width="500"
      :before-close="handleClose"
    >
      <el-form
        v-if="type == 'detail'"
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="姓名">{{ detailInfo.teacherName }}</el-form-item>
        <el-form-item label="手机号">{{ detailInfo.phoneNum }}</el-form-item>
        <el-form-item label="年龄">{{ detailInfo.age }}</el-form-item>
        <el-form-item label="昵称">{{ detailInfo.nickName }}</el-form-item>
        <el-form-item label="头像">
          <img
            v-if="detailInfo.avatarUrl"
            :src="detailInfo.avatarUrl"
            class="avatar"
          />
        </el-form-item>
        <el-form-item label="所属门店">{{ detailInfo.storeName }}</el-form-item>
        <el-form-item label="入职时间">{{ detailInfo.enterTime }}</el-form-item>
        <el-form-item label="状态">{{ detailInfo.statusName }}</el-form-item>
        <el-form-item label="专业技能">
          <span v-for="(item, index) in detailInfo.skills" :key="index"
            >{{ item.skillName }}
            <i v-if="index != detailInfo.skills.length - 1">,</i></span
          >
        </el-form-item>
        <el-form-item label="生日">{{ detailInfo.birthdayStr }}</el-form-item>
        <el-form-item label="介绍">{{ detailInfo.description }}</el-form-item>
      </el-form>

      <el-form
        v-else
        ref="ruleFormRef"
        style="max-width: 600px"
        :model="ruleForm"
        status-icon
        :rules="rules"
        label-width="auto"
        class="demo-ruleForm"
      >
        <el-form-item label="姓名" prop="teacherName">
          <el-input
            v-model="ruleForm.teacherName"
            type="text"
            autocomplete="off"
            placeholder="请输入姓名"
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phoneNum">
          <el-input
            v-model="ruleForm.phoneNum"
            type="phoneNum"
            autocomplete="off"
            placeholder="请输入手机号"
          />
        </el-form-item>
        <el-form-item label="昵称" prop="nickName">
          <el-input
            v-model="ruleForm.nickName"
            type="text"
            autocomplete="off"
            placeholder="请输入昵称"
          />
        </el-form-item>
        <el-form-item label="老师状态" prop="status">
          <el-select
            v-model="ruleForm.status"
            size="large"
            placeholder="请选择老师状态"
          >
            <el-option
              v-for="item in teacherStatusList"
              :key="item.code"
              :label="item.name"
              :value="item.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="入职时间" prop="enterTime">
          <el-date-picker
            v-model="ruleForm.enterTime"
            size="large"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled-date="time => time > Date.now()"
            placeholder="请选择入职时间"
          />
        </el-form-item>
        <el-form-item label="年龄" prop="age">
          <el-input
            v-model="ruleForm.age"
            type="number"
            autocomplete="off"
            placeholder="请输入年龄"
          />
        </el-form-item>

        <el-form-item label="所属门店" prop="storeId">
          <el-select
            v-model="ruleForm.storeId"
            size="large"
            placeholder="请选择所属门店"
          >
            <el-option
              v-for="item in storeList"
              :key="item.id"
              :label="item.storeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="专业技能" prop="skills">
          <el-select
            v-model="ruleForm.skills"
            multiple
            size="large"
            placeholder="请选择专业技能"
          >
            <el-option
              v-for="item in skillList"
              :key="item.id"
              :label="item.skillName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :show-file-list="false"
            :action="uploadUrl"
            :data="{ type: 'teacher' }"
            :before-upload="beforeAvatarUpload"
            :on-success="handleAvatarSuccess"
          >
            <img
              v-if="ruleForm.avatar && !previewUrl"
              :src="ruleForm.avatar"
              class="avatar"
            />
            <img v-else-if="previewUrl" :src="previewUrl" class="avatar" />
            <div v-else>
              <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
              <div class="upload-text">请上传头像</div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="出生日期" prop="birthdayStr">
          <el-date-picker
            v-model="ruleForm.birthdayStr"
            size="large"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="请选择出生日期"
          />
        </el-form-item>
        <el-form-item label="介绍" prop="description">
          <el-input
            v-model="ruleForm.description"
            type="text"
            autocomplete="off"
            placeholder="请输入介绍"
          />
        </el-form-item>
        <el-form-item
          v-if="type != 'detail'"
          label="  "
          style="margin-top: 30px"
        >
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            提交
          </el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
.statement {
  height: 100%;
  overflow: hidden;
  padding: 10px;
  background-color: #fff;
  border-radius: 5px;
}

.search {
  width: 100%;
  margin-top: 24px;
  margin-bottom: 8px;
  display: flex;
  // align-items: center;
  flex-wrap: wrap;
  .c-input {
    width: 240px !important;
    margin-bottom: 16px;
    margin-right: 16px;
    --el-border-radius-base: 8px;
    --el-input-focus-border-color: var(--main-color) !important;
    --el-component-size: 40px;
  }

  .search-btn {
    padding-left: 15px;
    .c-btn {
      height: 38px;
      border-radius: 8px;
      box-shadow: 0 0 4px 0 rgba(0, 0, 0, 0.2);
    }
  }
}

.c-page__bg {
  width: 100%;
  height: 100%;
  margin-top: 25px;
  padding-bottom: 24px;
  flex-direction: column;
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
}

.c-text-primary {
  font-size: 14px;
  color: #1c9fff;
  white-space: nowrap;
  cursor: pointer;
  padding-left: 5px;
  padding-right: 5px;
}

.pagination-block {
  padding-top: 20px;
  padding-right: 10px;
  display: flex;
  justify-content: flex-end;
}

.c-dot-success,
.c-dot-info {
  width: 6px;
  height: 6px;
  margin-right: 6px;
  display: inline-block;
  border-radius: 50%;
  flex-shrink: 0;
  background-color: #43bf0a;
}

.c-dot-info {
  background-color: #bfbfbf;
}

.system-icon-content {
  min-height: 500px;
}

.flex-row {
  margin-bottom: 16px;
  display: flex;
  justify-content: center;
  font-size: 16px;
  color: #262626;
}

.back {
  display: flex;
  align-items: center;
  font-size: 18px;
  color: #1c9fff;

  .back-text {
    display: flex;
    align-items: center;
    padding-right: 5px;
    font-size: 16px;
    cursor: pointer;
  }

  .title {
    color: #8c8c8c;
    font-size: 16px;
  }
}
.c-drawer-form {
  .c-info__title {
    margin-top: 20px;
    margin-bottom: 20px;
    color: #262626;
    font-size: 16px;
  }
  .el-form-item {
    margin-left: 60px;
    margin-bottonm: 10px;
  }
}
.el-drawer__header {
  padding-bottom: 10px;
  border-bottom: 1px solid #dcdcdc;
  margin-bottom: 0;
}
.upload-text {
  font-size: 14px;
  color: #909399;
  margin-top: 8px;
  text-align: center;
}

// ... 上传图片 ...

.avatar-uploader,
.qrcode-uploader {
  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }
  }
}

.required-label::before {
  content: "*";
  color: var(--el-color-danger);
  margin-right: 4px;
}

// ... 其他样式 ...
.qrcode-uploader-icon,
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 80px;
  text-align: center;
  line-height: 100px;
}

.qrcode,
.avatar {
  width: 100px;
  height: 100px;
  display: block;
}

.description-cell {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 150px;
  cursor: pointer;
}
</style>
